package com.auto.survey.log

import com.auto.survey.base.CustomApplication

class CrashHandler : Thread.UncaughtExceptionHandler {
    private val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
    private val logger = AppLogger.getInstance(CustomApplication.getContext())

    companion object {
        @Volatile
        private var instance: CrashHandler? = null

        fun install() {
            if (instance == null) {
                synchronized(CrashHandler::class) {
                    if (instance == null) {
                        instance = CrashHandler()
                        Thread.setDefaultUncaughtExceptionHandler(instance)
                    }
                }
            }
        }
    }

    override fun uncaughtException(t: Thread, e: Throwable) {
        try {
            logger.logCrash(e)
            // 可添加上传崩溃日志的逻辑
        } catch (ex: Exception) {
            ex.printStackTrace()
        } finally {
            // 确保原始处理程序仍被调用
            defaultHandler?.uncaughtException(t, e)
        }
    }
}